<?php
declare(strict_types=1);

namespace App\Repository;

use Hyperf\Di\Annotation\Inject;
use App\Exception\BusinessException;
use Hyperf\Contract\StdoutLoggerInterface;

/**
 * repository基类.
 */
class BaseRepository
{
	#[Inject]
    protected StdoutLoggerInterface $logger;

	/**
	 * 分页参数修正
	 * @param array $pageParamsList 分页参数
	 * @param int $maxPageSize 每页最大数量
	 * @return array
	 */
	protected final function pageParamsRevise(array $pageParamsList, int $maxPageSize = 50): array
	{
		$page = $pageParamsList['page'] ?? 1;
		$pageParamsList['page'] = max(1, (int)$page);
		$pageSize = $pageParamsList['page_size'] ?? 10;
		$pageParamsList['page_size'] = max(1, min((int)$pageSize, $maxPageSize));
		return $pageParamsList;
	}

	/**
	 * 分页数据格式化
	 * @param object $paginateData 分页数据
	 * @return array
	 */
	protected final function paginate(object $paginateData): array
	{
		$paginateDataArray = $paginateData->toArray();
		return [
			'total' => $paginateDataArray['total'],
			'page' => $paginateDataArray['current_page'],
			'page_size' => $paginateDataArray['per_page'],
			'list' => $paginateDataArray['data']
		];
	}

    /**
     * 规则验证
     * @param array $params 参数
     * @param array $rule 规则
     * @return array
     */
    protected function verify(array $params, array $rule) : array
    {
        $validator = $this->validationFactory->make($params, $rule);

        if ($validator->fails()) {
            $errorMessage = $validator->errors()->first();
            throw new BusinessException('40002', $errorMessage);
        }
        return [true, 'ok'];
    }
}